/*
 * @Author Baorong Yu
 * @Email: y15195965752@163.com
 * @Address: 浙江省杭州市余杭区赛银国际12幢4楼
 * @Date 2022/8/3 17:27
 * @Description moj_app
 */
import 'package:flutter/material.dart';
import 'package:flutter_uikit/flutter_uikit.dart';
import 'package:flutter_uikit/ui_text.dart';

class UIFloatExpendButton extends StatefulWidget {
  //按钮图标
  final List<FEButtonModel> iconList;

  //按钮高度
  final double fabHeight;

  //主菜单按钮图标大小
  final double iconsize;

  //选项卡按钮间隔
  final double tabspace;

  //绝对定位上
  final double? top;

  //绝对定位上
  final double? bottom;

  //绝对定位上
  final double? left;

  //绝对定位上
  final double? right;

  //选项卡按钮颜色
  final int tabcolor;

  //主菜单卡收起后颜色
  final int MainTabBeginColor;

  //主菜单卡展开后颜色
  final int MainTabAfterColor;

  //主菜单卡变化图标（动画图标）
  final AnimatedIconData MainAnimatedIcon;

  //选项卡类型即展开方向
  final ButtonType type;

  final Alignment? alignment;

  //按钮的点击事件
  final Function(int index) callback;

  UIFloatExpendButton(this.iconList,
      {required this.callback,
      this.fabHeight = 30,
      this.tabspace = 20,
      this.tabcolor = 0xFF476CFF,
      this.MainTabBeginColor = 0xFF476CFF,
      this.MainTabAfterColor = 0xFF476CFF,
      this.MainAnimatedIcon = AnimatedIcons.menu_close,
      this.iconsize = 15,
      this.type = ButtonType.Top,
      this.alignment,
      this.top,
      this.bottom,
      this.left,
      this.right});

  @override
  _UIFloatExpendState createState() => _UIFloatExpendState();
}

//旋转变换按钮 向上弹出的效果 State实现
class _UIFloatExpendState extends State<UIFloatExpendButton>
    with SingleTickerProviderStateMixin {
  //记录是否打开
  bool isOpened = false;

  //动画控制器
  late AnimationController _animationController;

  //颜色变化取值
  late Animation<Color?> _animateColor;

  //图标变化取值
  late Animation<double> _animateIcon;

  //按钮的位置动画
  late Animation<double> _fabtween;

  //动画执行速率
  Curve _curve = Curves.easeOut;

  @override
  initState() {
    super.initState();
    //初始化动画控制器
    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 300));
    //添加动画监听
    _animationController.addListener(() {
      setState(() {});
    });
    //Tween结合_animationController，使300毫秒内执行一个从0.0到0.1的变换过程
    _animateIcon =
        Tween<double>(begin: 0.0, end: 1.0).animate(_animationController);
    //结合_animationController 实现一个从Colors.blue到Colors.deepPurple的动画过渡
    _animateColor = ColorTween(
      begin: Color(widget.MainTabBeginColor),
      end: Color(widget.MainTabAfterColor),
    ).animate(CurvedAnimation(parent: _animationController, curve: _curve));

    _fabtween = Tween<double>(
      begin: 0,
      end: _getfabtweenAfter(),
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Interval(
        0.0,
        0.75,
        curve: _curve,
      ),
    ));
  }

  //根据类型获取变化结束值
  double _getfabtweenAfter() {
    if (widget.type == ButtonType.Right || widget.type == ButtonType.Bottom) {
      return widget.fabHeight + widget.tabspace;
    } else {
      return -(widget.fabHeight + widget.tabspace);
    }
  }

  //根据类型获取X轴移动数值
  double _getfabtranslateX(int i) {
    if (widget.type == ButtonType.Left || widget.type == ButtonType.Right) {
      return _fabtween.value * (i + 1);
    } else {
      return 0;
    }
  }

  //根据类型获取Y轴移动数值
  double _getfabtranslateY(int i) {
    if (widget.type == ButtonType.Top || widget.type == ButtonType.Bottom) {
      return _fabtween.value * (i + 1);
    } else {
      return 0;
    }
  }

  //根据类型获取主菜单位置
  // AlignmentGeometry _getAligment() {
  //   if (widget.type == ButtonType.Top) {
  //     return Alignment.bottomCenter;
  //   } else if (widget.type == ButtonType.Left) {
  //     return Alignment.centerRight;
  //   } else if (widget.type == ButtonType.Bottom) {
  //     return Alignment.topCenter;
  //   } else {
  //     return Alignment.centerLeft;
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    //构建子菜单
    return isOpened
        ? Scaffold(
            backgroundColor: Color(0x00000000),
            body: GestureDetector(
              onTap: () => {
                isOpened = !isOpened,
                _animationController.reverse()
              },
              child: Container(
                color: Color(0x00),
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                child: _body(),
              ),
            ),
          )
        : _body();
  }

  //构建固定旋转菜单按钮
  Widget floatButton() {
    return Container(
      width: widget.fabHeight,
      height: widget.fabHeight,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(widget.fabHeight),
        boxShadow: [
          BoxShadow(
            color: Color(0x75173ED9),
            offset: Offset(0, 3),
            blurRadius: 5,
            spreadRadius: 1,
          )
        ],
      ),
      child: FloatingActionButton(
        //通过_animateColor实现背景颜色的过渡
        backgroundColor: _animateColor.value, // _animateColor.value
        onPressed: floatClick,
        elevation: 0.5,
        //通过AnimatedIcon实现标签的过渡
        shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(widget.fabHeight)),
        child: AnimatedIcon(
          icon: widget.MainAnimatedIcon,
          size: widget.iconsize,
          progress: _animateIcon,
          color: Colors.white,
        ),
      ),
    );
  }

  //FloatingActionButton的点击事件，用来控制按钮的动画变换
  floatClick() {
    if (!isOpened) {
      // OverlayView.addOverlayEntry(Scaffold(
      //   backgroundColor: Color(0x40000000),
      //   body: _body(),
      // ));
      _animationController.forward(); //展开动画
    } else {
      // UIOverlay.dismiss();
      _animationController.reverse(); //收回动画
    }
    isOpened = !isOpened;
  }

  Widget _body() {
    List<Widget> itemList = [];

    for (int i = 0; i < widget.iconList.length; i++) {
      //通过Transform来促成FloatingActionButton的平移
      itemList.add(
        Transform(
          transform: Matrix4.translationValues(
              _getfabtranslateX(i), _getfabtranslateY(i), 0.0),
          child: Column(
            children: [
              Container(
                width: widget.fabHeight,
                height: widget.fabHeight,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(widget.fabHeight),
                  boxShadow: [
                    BoxShadow(
                      color: Color(0x75173ED9),
                      offset: Offset(0, 3),
                      blurRadius: 5,
                      spreadRadius: 1,
                    )
                  ],
                ),
                child: FloatingActionButton(
                  heroTag: "$i",
                  elevation: 0.5,
                  backgroundColor: Color(widget.tabcolor),
                  shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(widget.fabHeight)),
                  onPressed: () {
                    // //点击菜单子选项要求菜单弹缩回去
                    //if(isOpened){
                    floatClick();
                    widget.callback(i);
                    //}
                  },
                  child: widget.iconList[i].icon,
                ),
              ),
              isOpened
                  ? UIText(
                      data: widget.iconList[i].title!,
                      fontSize: 12,
                      color: 0xFF000000,
                      padding: EdgeInsets.only(top: 2),
                    )
                  : Container()
            ],
          ),
        ),
      );
    }
    return Stack(
      children: [
        Positioned(
            top: widget.top,
            left: widget.left,
            right: widget.right,
            bottom: widget.bottom,
            child: Column(
              children: [
                Stack(
                  alignment: Alignment.bottomCenter,
                  children: [
                    widget.type == ButtonType.Left ||
                            widget.type == ButtonType.Right
                        ? SizedBox(
                            width: (widget.fabHeight + widget.tabspace) *
                                    widget.iconList.length +
                                widget.fabHeight)
                        : SizedBox(
                            height: (widget.fabHeight + widget.tabspace) *
                                    widget.iconList.length +
                                widget.fabHeight),
                  ] //根据横纵情况拓展点击区域
                    ..addAll(itemList)
                    ..add(Positioned(
                      child: floatButton(),
                    )),
                )
              ],
            ))
      ],
    );
  }

  //页面销毁时，销毁动画控制器
  @override
  dispose() {
    _animationController.dispose();
    super.dispose();
  }
}

class FEButtonModel {
  final Icon? icon;
  final String? title;
  // final String? route;

  FEButtonModel({
    this.icon,
    this.title,
    // this.route,
  });

  factory FEButtonModel.formMap(Map data) {
    Icon icon = data["icon"] ?? 0;
    String title = data["title"] ?? '';
    // String route = data["route"];
    return FEButtonModel(
      icon: icon,
      title: title,
      // route: route,
    );
  }

  static List<FEButtonModel> modelList(List modelList) {
    List<FEButtonModel> list = <FEButtonModel>[];
    modelList.forEach((element) {
      list.add(FEButtonModel.formMap(element));
    });
    return list;
  }
}

enum ButtonType { Left, Right, Top, Bottom }
